package com.example.everying.service.school.impl;/*
 * 项目名称: everything
 * 文件名: SchoolServiceImpl
 * 作者: 张泽阳
 * 日期: 2025/5/19
 * 描述:
 */

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.context.UserContext;
import com.example.everying.mapper.school.SchoolMapper;
import com.example.everying.mapper.user.UserMapper;
import com.example.everying.model.dto.school.SchoolPageDto;
import com.example.everying.model.entity.school.SchoolEntity;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.school.SchoolInfoVo;
import com.example.everying.service.school.SchoolService;
import com.example.everying.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SchoolServiceImpl  extends ServiceImpl<SchoolMapper, SchoolEntity> implements SchoolService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<SchoolEntity> selectPage(Page<SchoolEntity> pageParam, SchoolPageDto schoolPageDto) {
        SchoolEntity schoolEntity = new SchoolEntity();
        QueryWrapper<SchoolEntity> wrapper = new QueryWrapper<>();
        if (schoolPageDto.getSchoolName() != null){
            wrapper.like("school_name",schoolPageDto.getSchoolName());
        }
        IPage<SchoolEntity> schoolEntityPage = baseMapper.selectPage(pageParam, wrapper);
        return schoolEntityPage;
    }

    @Override
    public Result<?> updateSchool(SchoolEntity schoolEntity) {
        UserEntity user = UserContext.getUser();
        String schoolId = user.getSchoolId();
        if(schoolId.isEmpty()){
            return Result.fail("请先绑定学校");
        }
        if (user.getIsAdministrator() != 3){
            return Result.fail("权限不足");
        }
        schoolEntity.setId(schoolId);
        baseMapper.updateById(schoolEntity);
        SchoolEntity school = baseMapper.selectById(schoolId);
        return Result.ok(school);
    }

    @Override
    public Result<?> querySchoolById(String id) {
        SchoolInfoVo schoolInfoVo = new SchoolInfoVo();
        SchoolEntity schoolEntity = baseMapper.selectById(id);
        BeanUtil.copyProperties(schoolEntity,schoolInfoVo);
        schoolInfoVo.setAdminList(userMapper.getUserByAdmin(3));

        return Result.ok(schoolInfoVo);
    }

    @Override
    public SchoolEntity getSchoolByName(String name) {
        QueryWrapper<SchoolEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("school_name",name);
        SchoolEntity schoolEntity = baseMapper.selectOne(wrapper);
        return schoolEntity;
    }
}
